package com.runnor.common.websys.system.security;

import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import com.runnor.common.websys.system.entity.ApiResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author runnor-yh
 * @date 2023年08月15日 11:06
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Value("${app.security.auth_key}")
    private String authKey;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();

        LoginUser principal = (LoginUser) authentication.getPrincipal();
        Map map = new LinkedHashMap<>();
        // 生成JWT，并放置到请求头中
//        map.put("principal", principal);
        map.put("userid", principal.getUserId());
        map.put("username", principal.getUsername());
        map.put("authorities", AuthorityUtils.authorityListToSet(principal.getAuthorities()));
        map.put("expire_time", System.currentTimeMillis() + 3600 * 1000 * 8);
        String token = JWTUtil.createToken(map, authKey.getBytes());
        response.setHeader("Authorization", token);
        outputStream.write(JSONUtil.toJsonStr(ApiResult.ok(token)).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
